/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VendaForm.java
 *
 * Created on 02/05/2010, 14:01:30
 */
package loja.gui;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import loja.dao.ClienteDao;
import loja.dao.JdbcUtils;
import loja.dao.ProdutoDao;
import loja.dao.VendaDao;
import loja.dao.exceptions.BuscaException;
import loja.dao.exceptions.ImpossivelCriarException;
import loja.dominio.Cliente;
import loja.dominio.FormaDePagamento;
import loja.dominio.ItemDeVenda;
import loja.dominio.Produto;
import loja.dominio.Venda;
import loja.gui.tablemodel.ItemDeVendaTableModel;
import loja.gui.utils.MessageUtil;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;

/**
 *
 * @author Rodrigo
 */
public class VendaForm extends javax.swing.JFrame implements TableModelListener{

    private Venda venda;
    private Cliente cliente;
    private ItemDeVendaTableModel model;
    private VendaDao vendaDao;

    /** Creates new form VendaForm */
    public VendaForm() {
        model = new ItemDeVendaTableModel();
        initComponents();
        tabelaItemVenda.setModel(model);
        model.addTableModelListener(this);
        bntExcluir.setEnabled(false);
    }

    public void setItemCodeText(String codigo) {
        txtCodigo.setText(codigo);
    }

    public void setItemCodeTexto(String codCliente) {
        txtCodigoCliente.setText(codCliente);
    }

    private void reiniciarVenda() {
        venda = null;
        txtCodigo.setText("");
        txtQuantidade.setText("1");
        txtCodigo.requestFocus();
        lblValorTotal.setText("0.0");
        txtCodigoCliente.setText("");
        lblNomeCompleto.setText("");
        rdbntDinheiro.setSelected(true);
        model.limpar();
    }
   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pagamentoGrupo = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        lblCodigo = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        lblQuantidade = new javax.swing.JLabel();
        txtQuantidade = new javax.swing.JTextField();
        btnInserirItem = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        lblCodigoCliente = new javax.swing.JLabel();
        txtCodigoCliente = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JButton();
        lblNomeCompleto = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        rdbntDinheiro = new javax.swing.JRadioButton();
        rdbtnCheque = new javax.swing.JRadioButton();
        rdbtnCartaoDebito = new javax.swing.JRadioButton();
        rdbtnCartaoCredito = new javax.swing.JRadioButton();
        jPanel4 = new javax.swing.JPanel();
        lblTotal = new javax.swing.JLabel();
        lblValorTotal = new javax.swing.JLabel();
        btnFecharVenda = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaItemVenda = new javax.swing.JTable();
        bntExcluir = new javax.swing.JButton();
        bntSair = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Gerar Venda ");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Início"));
        jPanel1.setName("jPanel1"); // NOI18N

        lblCodigo.setFont(new java.awt.Font("Tahoma", 1, 24));
        lblCodigo.setText("Código");
        lblCodigo.setName("lblCodigo"); // NOI18N

        txtCodigo.setFont(new java.awt.Font("Tahoma", 1, 24));
        txtCodigo.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtCodigo.setName("txtCodigo"); // NOI18N
        txtCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCodigoActionPerformed(evt);
            }
        });

        lblQuantidade.setFont(new java.awt.Font("Tahoma", 1, 24));
        lblQuantidade.setText("Quantidade");
        lblQuantidade.setName("lblQuantidade"); // NOI18N

        txtQuantidade.setFont(new java.awt.Font("Tahoma", 1, 24));
        txtQuantidade.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtQuantidade.setText("1");
        txtQuantidade.setName("txtQuantidade"); // NOI18N
        txtQuantidade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtQuantidadeActionPerformed(evt);
            }
        });

        btnInserirItem.setFont(new java.awt.Font("Tahoma", 1, 24));
        btnInserirItem.setText("Inserir Item");
        btnInserirItem.setName("btnInserirItem"); // NOI18N
        btnInserirItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInserirItemActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Código = 0 (Zero) para Pesquisar o codigo Produto.");
        jLabel1.setName("jLabel1"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lblCodigo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCodigo, javax.swing.GroupLayout.DEFAULT_SIZE, 351, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblQuantidade)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnInserirItem))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(129, 129, 129)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCodigo)
                    .addComponent(btnInserirItem)
                    .addComponent(txtQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblQuantidade)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Dados do Cliente"));
        jPanel2.setName("jPanel2"); // NOI18N

        lblCodigoCliente.setFont(new java.awt.Font("Tahoma", 1, 24));
        lblCodigoCliente.setText("Código");
        lblCodigoCliente.setName("lblCodigoCliente"); // NOI18N

        txtCodigoCliente.setFont(new java.awt.Font("Tahoma", 1, 24));
        txtCodigoCliente.setName("txtCodigoCliente"); // NOI18N
        txtCodigoCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCodigoClienteActionPerformed(evt);
            }
        });

        btnBuscar.setFont(new java.awt.Font("Tahoma", 1, 24));
        btnBuscar.setText("Buscar");
        btnBuscar.setName("btnBuscar"); // NOI18N
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        lblNomeCompleto.setFont(new java.awt.Font("Tahoma", 1, 24));
        lblNomeCompleto.setName("lblNomeCompleto"); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(lblNomeCompleto, javax.swing.GroupLayout.DEFAULT_SIZE, 880, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(lblCodigoCliente)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCodigoCliente, javax.swing.GroupLayout.DEFAULT_SIZE, 670, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnBuscar)
                        .addGap(10, 10, 10))))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblCodigoCliente)
                    .addComponent(txtCodigoCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBuscar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblNomeCompleto, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Forma de Pagamento"));
        jPanel3.setName("jPanel3"); // NOI18N

        pagamentoGrupo.add(rdbntDinheiro);
        rdbntDinheiro.setFont(new java.awt.Font("Tahoma", 1, 24));
        rdbntDinheiro.setSelected(true);
        rdbntDinheiro.setText("Dinheiro");
        rdbntDinheiro.setName("rdbntDinheiro"); // NOI18N
        rdbntDinheiro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdbntDinheiroActionPerformed(evt);
            }
        });

        pagamentoGrupo.add(rdbtnCheque);
        rdbtnCheque.setFont(new java.awt.Font("Tahoma", 1, 24));
        rdbtnCheque.setText("Cheque");
        rdbtnCheque.setName("rdbtnCheque"); // NOI18N
        rdbtnCheque.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdbtnChequeActionPerformed(evt);
            }
        });

        pagamentoGrupo.add(rdbtnCartaoDebito);
        rdbtnCartaoDebito.setFont(new java.awt.Font("Tahoma", 1, 24));
        rdbtnCartaoDebito.setText("Cartão de Débito");
        rdbtnCartaoDebito.setName("rdbtnCartaoDebito"); // NOI18N
        rdbtnCartaoDebito.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdbtnCartaoDebitoActionPerformed(evt);
            }
        });

        pagamentoGrupo.add(rdbtnCartaoCredito);
        rdbtnCartaoCredito.setFont(new java.awt.Font("Tahoma", 1, 24));
        rdbtnCartaoCredito.setText("Cartão de Crédito");
        rdbtnCartaoCredito.setName("rdbtnCartaoCredito"); // NOI18N
        rdbtnCartaoCredito.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdbtnCartaoCreditoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(rdbtnCheque)
                    .addComponent(rdbntDinheiro))
                .addGap(6, 6, 6)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(rdbtnCartaoDebito)
                    .addComponent(rdbtnCartaoCredito)))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rdbntDinheiro)
                    .addComponent(rdbtnCartaoDebito))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rdbtnCheque)
                    .addComponent(rdbtnCartaoCredito)))
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Total"));
        jPanel4.setName("jPanel4"); // NOI18N

        lblTotal.setFont(new java.awt.Font("Tahoma", 1, 24));
        lblTotal.setText("TOTAL (R$)");
        lblTotal.setName("lblTotal"); // NOI18N

        lblValorTotal.setFont(new java.awt.Font("Tahoma", 1, 24));
        lblValorTotal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblValorTotal.setText("0,00");
        lblValorTotal.setName("lblValorTotal"); // NOI18N

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTotal)
                .addGap(30, 30, 30)
                .addComponent(lblValorTotal, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblValorTotal)
                    .addComponent(lblTotal))
                .addContainerGap(34, Short.MAX_VALUE))
        );

        btnFecharVenda.setFont(new java.awt.Font("Tahoma", 1, 24));
        btnFecharVenda.setText("Fechar Venda e Imprimir nota Fiscal");
        btnFecharVenda.setName("btnFecharVenda"); // NOI18N
        btnFecharVenda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFecharVendaActionPerformed(evt);
            }
        });

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel5.setName("jPanel5"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tabelaItemVenda.setGridColor(new java.awt.Color(255, 255, 255));
        tabelaItemVenda.setName("tabelaItemVenda"); // NOI18N
        tabelaItemVenda.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaItemVendaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabelaItemVenda);

        bntExcluir.setFont(new java.awt.Font("Tahoma", 1, 12));
        bntExcluir.setText("Excluir");
        bntExcluir.setName("bntExcluir"); // NOI18N
        bntExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntExcluirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap(829, Short.MAX_VALUE)
                .addComponent(bntExcluir))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 900, Short.MAX_VALUE)
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bntExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        bntSair.setFont(new java.awt.Font("Tahoma", 1, 11));
        bntSair.setText("Sair");
        bntSair.setName("bntSair"); // NOI18N
        bntSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntSairActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(bntSair))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnFecharVenda, javax.swing.GroupLayout.DEFAULT_SIZE, 520, Short.MAX_VALUE)
                            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(bntSair)
                    .addComponent(btnFecharVenda, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-948)/2, (screenSize.height-614)/2, 948, 614);
    }// </editor-fold>//GEN-END:initComponents

    private void rdbntDinheiroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdbntDinheiroActionPerformed
        venda.setFormaDePagamento(FormaDePagamento.DINHEIRO);
    }//GEN-LAST:event_rdbntDinheiroActionPerformed

    private void rdbtnChequeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdbtnChequeActionPerformed
        venda.setFormaDePagamento(FormaDePagamento.CHEQUE);
    }//GEN-LAST:event_rdbtnChequeActionPerformed

    private void btnInserirItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInserirItemActionPerformed
        ProdutoDao dao = new ProdutoDao();
        Produto produto = null;
        ItemDeVenda item = new ItemDeVenda();
        String sId = txtCodigo.getText();
        String sQuantidade = txtQuantidade.getText();
        long id = 0;
        int quantidade = 1;
        PesquisaProdutoForm ppf = null;
        bntExcluir.setEnabled(false);


        try {
            if (venda == null) {
                venda = new Venda();
                venda.setFormaDePagamento(FormaDePagamento.DINHEIRO);
                venda.setData(new Date());
            }

            try {
                id = Long.parseLong(sId);
                if (sId.equals("0")) {
                    ppf = new PesquisaProdutoForm();
                    ppf.setChamador(this);
                    ppf.setVisible(true);
                    sId = txtCodigo.getText();
                    id = Long.parseLong(sId);
                }

            } catch (NumberFormatException ex) {
                if (sId == null || sId.equals("")) {
                    ppf = new PesquisaProdutoForm();
                    ppf.setChamador(this);
                    ppf.setVisible(true);
                    sId = txtCodigo.getText();
                    id = Long.parseLong(sId);
                } else {
                    MessageUtil.errorMessage(this, "Por favor, informe um número no campo código.");
                    return;
                }
            }
            produto = dao.buscar(id);
            if(produto != null) {
                venda.setId(id);
                } else {
                    MessageUtil.errorMessage(this, "Produto não encontrado. Por favor, informe um código válido.");
                    return;
                }
            item.setProduto(produto);
            try {
                if (sQuantidade != null && !sQuantidade.equals("") && !sQuantidade.equals("0")) {
                    quantidade = Integer.parseInt(sQuantidade);
                    item.setQuantidade(quantidade);
                }
            } catch (NumberFormatException numberFormatException) {
                MessageUtil.errorMessage(this, "Por favor, informe um número no campo código.");
                return;
            }

            item.setVenda(venda);
            venda.inserirItem(item);
            model.addItemDeVenda(item);
            
          //  lblValorTotal.setText("" + venda.total());
          
            txtCodigo.setText("");
            txtQuantidade.setText("1");
            txtCodigo.requestFocus();
            } catch (BuscaException ex) {
            MessageUtil.errorMessage(this, "Não foi possível localizar o Produto informado. Informe um código válido.");
        }

    }//GEN-LAST:event_btnInserirItemActionPerformed

    private void txtQuantidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtQuantidadeActionPerformed
        btnInserirItemActionPerformed(evt);
    }//GEN-LAST:event_txtQuantidadeActionPerformed

    private void txtCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCodigoActionPerformed
        btnInserirItemActionPerformed(evt);
    }//GEN-LAST:event_txtCodigoActionPerformed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        ClienteDao clienteDao = new ClienteDao();

        String clienteId = txtCodigoCliente.getText();
        long id;
        PesquisaClienteForm ppf = null;

        try {
            id = Long.parseLong(clienteId);

            if (clienteId.equals("0")) {
                ppf = new PesquisaClienteForm();
                ppf.setChamador(this);
                ppf.setVisible(true);
            }else{

            try {
                cliente = clienteDao.buscar(id);
                if(cliente != null) {
                venda.setCliente(cliente);
                } else {
                    MessageUtil.errorMessage(this, "Cliente não encontrado. Por favor, informe um código válido.");
                    return;
                }
            } catch (BuscaException ex) {
                if (clienteId == null || clienteId.equals("")) {
                    ppf = new PesquisaClienteForm();
                    ppf.setChamador(this);
                    ppf.setVisible(true);
                } else {
                    MessageUtil.errorMessage(this, "Por favor, informe um número no campo código.");
                    return;
                }
            }
            }
            lblNomeCompleto.setText(cliente.getNome());
        } catch (NumberFormatException numberFormatException) {
            MessageUtil.errorMessage(this, "O código do cliente deve ser um número.");
        }
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnFecharVendaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFecharVendaActionPerformed
        int numeroDeItens = venda.getItens().size();
        try {
            if (numeroDeItens > 0) {
                vendaDao = new VendaDao();
                vendaDao.criar(venda);

                //abrir tela de relatorio da nota fiscal e passar a venda
                exibirNotaFiscal(venda);

                //ao fechar a tela de nota fiscal, volta tela de vendas pro estado inicial
                reiniciarVenda();
            }
        } catch (ImpossivelCriarException ex) {
            ex.printStackTrace();
            MessageUtil.errorMessage(this, "A venda não pode ser salva");
        } catch (SQLException ex) {
            ex.printStackTrace();
            MessageUtil.errorMessage(this, "A venda não pode ser salva");
        } catch (JRException ex) {
            ex.printStackTrace();
            MessageUtil.errorMessage(this, "A nota fiscal não pode ser mostrada");
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            MessageUtil.errorMessage(this, "O modelo da nota fiscal não foi encontrado");
        }

    }//GEN-LAST:event_btnFecharVendaActionPerformed

    private void txtCodigoClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCodigoClienteActionPerformed
        btnBuscarActionPerformed(evt);
    }//GEN-LAST:event_txtCodigoClienteActionPerformed

    private void rdbtnCartaoDebitoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdbtnCartaoDebitoActionPerformed
        venda.setFormaDePagamento(FormaDePagamento.CARTAO_DE_DEBITO);

    }//GEN-LAST:event_rdbtnCartaoDebitoActionPerformed

    private void rdbtnCartaoCreditoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdbtnCartaoCreditoActionPerformed
        venda.setFormaDePagamento(FormaDePagamento.CARTAO_DE_CREDITO);
    }//GEN-LAST:event_rdbtnCartaoCreditoActionPerformed

    private void tabelaItemVendaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaItemVendaMouseClicked
        int linha = tabelaItemVenda.getSelectedRow();

        if (linha != -1) {
            bntExcluir.setEnabled(true);
        }

    }//GEN-LAST:event_tabelaItemVendaMouseClicked

    private void bntExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntExcluirActionPerformed
        ItemDeVenda item = null;
        int linha = -1;
        try {
            int resposta = JOptionPane.showConfirmDialog(this, "Deseja realmente Excluir esse Item de Venda?",
                    "Confirmação", JOptionPane.YES_NO_OPTION);

            if (resposta == JOptionPane.YES_NO_OPTION) {
                linha = tabelaItemVenda.getSelectedRow();
                item = model.getItemDeVenda(linha);

                venda.excluirItem(item);
                model.excluirItemDeVenda(item);
                bntExcluir.setEnabled(false);               
            }
        } catch (Exception ex) {
            bntExcluir.setEnabled(false);
            MessageUtil.errorMessage(this, "Ocorreu um erro ao excluir o cliente: " + ex.getMessage());
        }
        //       venda.excluirItem(itemExclusa);


    }//GEN-LAST:event_bntExcluirActionPerformed

    private void bntSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntSairActionPerformed
         this.dispose();
    }//GEN-LAST:event_bntSairActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bntExcluir;
    private javax.swing.JButton bntSair;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnFecharVenda;
    private javax.swing.JButton btnInserirItem;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JLabel lblCodigoCliente;
    private javax.swing.JLabel lblNomeCompleto;
    private javax.swing.JLabel lblQuantidade;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JLabel lblValorTotal;
    private javax.swing.ButtonGroup pagamentoGrupo;
    private javax.swing.JRadioButton rdbntDinheiro;
    private javax.swing.JRadioButton rdbtnCartaoCredito;
    private javax.swing.JRadioButton rdbtnCartaoDebito;
    private javax.swing.JRadioButton rdbtnCheque;
    private javax.swing.JTable tabelaItemVenda;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtCodigoCliente;
    private javax.swing.JTextField txtQuantidade;
    // End of variables declaration//GEN-END:variables

    private void exibirNotaFiscal(Venda venda) throws JRException, SQLException, FileNotFoundException {


        String caminhoRelJasper = "./reports/nota_fiscal.jasper";

        Connection connection = JdbcUtils.getConexao();
        InputStream relJasper = new FileInputStream(caminhoRelJasper);
        Map parametros = new HashMap();
        JasperPrint impressao = null;
        JasperReport relatorioJasper = (JasperReport) JRLoader.loadObject(relJasper);
        parametros.put("ID_VENDA", venda.getId());
        parametros.put("SUBREPORT_DIR", "./reports/");
        impressao = JasperFillManager.fillReport(relatorioJasper, parametros, connection);
        NotaFiscalDialog dialog = new NotaFiscalDialog(this, true, impressao);
        dialog.setVisible(true);
//        JasperViewer viewer = new JasperViewer(impressao, true);
//        viewer.setVisible(true);

    }

    public void tableChanged(TableModelEvent e) {
        lblValorTotal.setText("" + venda.total());
    }
}
